package com.cn.music.view;

import android.util.Log;

import androidx.lifecycle.LiveData;
import androidx.lifecycle.MutableLiveData;
import androidx.lifecycle.ViewModel;

import com.cn.music.model.LoginModel;
import com.cn.music.model.RegisterModel;
import com.cn.music.server.Api;
import com.cn.music.server.Constant;

import java.util.ArrayList;
import java.util.List;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * @Auth: 陈彬
 * @Date: 2020/9/28 9:30
 */
public class RegisterViewModel extends ViewModel {

    private Retrofit retrofit;
    private MutableLiveData<List<RegisterModel>> registerModel;
    private final String TAG = "RegisterViewModel";

    public LiveData<List<RegisterModel>> loadRegisterModel(String phone, String password, String code, String nickname) {
        if (registerModel == null) {
            registerModel = new MutableLiveData<>();
            responseRegisterModel(phone, password, code, nickname);
        }
        return registerModel;
    }

    private void responseRegisterModel(String phone, String password, String code, String nickname) {
        retrofit = new Retrofit.Builder()
                .baseUrl(Constant.BASE_URL)
                // 要加这个不然会报java.lang.IllegalArgumentException
                .addConverterFactory(GsonConverterFactory.create())
                .build();

        // 创建代理对象
        Api api = retrofit.create(Api.class);

        Call<RegisterModel> call = api.register(phone, password, code, nickname);

        call.enqueue(new Callback<RegisterModel>() {
            @Override
            public void onResponse(Call<RegisterModel> call, Response<RegisterModel> response) {
                RegisterModel model = response.body();
                Log.e(TAG,"请求信息:"+response.body());
                List<RegisterModel> models = new ArrayList<>();
                models.add(model);
                registerModel.setValue(models);
            }

            @Override
            public void onFailure(Call<RegisterModel> call, Throwable t) {
                Log.e(TAG,"错误请求:"+t.getMessage());
            }
        });

    }


}
